package com.nineclock.system.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.sms.AliyunSmsUtils;
import com.nineclock.system.dto.SysUserDTO;
import com.nineclock.system.processor.SendMessageProcessor;
import com.nineclock.system.service.SmsService;
import com.nineclock.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import java.time.Duration;
import java.util.List;


@Service
@Transactional
@Slf4j
public class SmsServiceImpl implements SmsService {

    @Autowired
    private SysUserService userService;

/*    @Autowired
    private AliyunSmsUtils smsUtils;*/

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Value("${restApi}")
    private String restApi;

    @Autowired
    private List<SendMessageProcessor> sendMessageProcessorList;

    @Override
    public void sendSms(String mobile, String type) {
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(type)){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        SysUserDTO sysUserDTO = userService.queryUser(mobile);
        //如果是注册判断手机号有没有被注册
        if (type.equals(SMSConstant.SMS_TYPE_REGISTER)){
            if (sysUserDTO!=null){
                throw new NcException(ResponseEnum.USER_MOBILE_EXISTS);
            }
        }else {
            if (sysUserDTO==null){
                throw new NcException(ResponseEnum.USER_NOT_REGISTER);
            }
        }
        String code = RandomUtil.randomNumbers(6);
        /*Boolean sendMessageResult = smsUtils.sendSMS(mobile, code);
        if (!sendMessageResult){
            throw new NcException(ResponseEnum.SEND_MESSAGE_ERROR);
        }*/
        String prefix = getPrefix(type);
        SendMessageProcessor sendMessageProcessor = chooseProcessor(restApi);
        Boolean sendMessageResult = sendMessageProcessor.sendSms(mobile, code);
        if (!sendMessageResult){
            throw new NcException(ResponseEnum.SEND_MESSAGE_ERROR);
        }
        redisTemplate.opsForValue().set(prefix+mobile,code, Duration.ofMinutes(1));
        log.info("短信发送成功，手机号 = " + mobile + "，业务类型 = " + type + "，验证码 = " + code);
    }
    public SendMessageProcessor chooseProcessor(String restApi){
        for (SendMessageProcessor processor : sendMessageProcessorList) {
            if (processor.support(restApi)){
                return processor;
            }
        }
        return null;
    }


    /**
     * 根据操作类型，获取验证码前缀
     * @param type
     * @return
     */
    private String getPrefix(String type){
        String prefix = "";
        switch (type){
            case "1":
                prefix = SMSConstant.SMS_LOGIN_KEY_PREFIX;//登录
                break;
            case "2":
                prefix = SMSConstant.SMS_REGISTER_KEY_PREFIX;//注册
                break;
            case "3":
                prefix = SMSConstant.SMS_CHANGE_MANAGER_KEY_PREFIX;//更改管理员
                break;
            case "4":
                prefix = SMSConstant.SMS_RESET_KEY_PREFIX;//重置密码
                break;
            default:
                break;
        }
        return prefix;
    }

    @Override
    public Boolean verifySmsCode(String mobile, String type, String checkcode) {
        // 参数校验
        if(StringUtils.isEmpty(mobile) || StringUtils.isEmpty(type) || StringUtils.isEmpty(checkcode)){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        // 获取发送的验证码，和传入的验证码进行对比
        String prefix = getPrefix(type);
        String redisCode = redisTemplate.opsForValue().get(prefix + mobile);

        if(!StringUtils.isEmpty(redisCode) && redisCode.equals(checkcode)){
            // 校验完验证码，删除验证码
            redisTemplate.delete(prefix + mobile);
            return true;
        }
        return false;
    }
}
